import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { login as loginApi } from "@/apis/auth.js";
import { useUserStore } from "@/store/modules/user.js";

export function useLogin() {
	const router = useRouter();
	const route = useRoute();
	const loading = ref(false);
	const userStore = useUserStore();

	// 表单数据
	const loginForm = reactive({
		username: "admin",
		password: "123456",
		rememberMe: false,
	});

	// 表单验证规则
	const loginRules = {
		username: [
			{ required: true, message: "请输入用户名", trigger: "blur" },
			{
				min: 1,
				max: 20,
				message: "用户名长度在 1 到 20 个字符",
				trigger: "blur",
			},
		],
		password: [
			{ required: true, message: "请输入密码", trigger: "blur" },
			{
				min: 1,
				max: 20,
				message: "密码长度在 1 到 20 个字符",
				trigger: "blur",
			},
		],
	};

	// 处理登录
	const handleLogin = async () => {
		loading.value = true;
		try {
			// 调用后端登录接口
			const response = await loginApi(loginForm);

			// 假设后端返回格式：{ code: 200, message: 'success', data: { token: 'xxx', username: 'xxx', roleType: 'xxx' } }
			const { code, message, data } = response;

			if (code === 200 && data) {
				// 存储token
				localStorage.setItem("token", data.token);

				// 使用userStore设置用户信息，包含userType
				userStore.setUserInfo({
					id: 1, // 实际应该从后端获取，暂时使用默认值
					username: data.username,
					userType: data.userType
				});

				// 如果勾选了记住密码，存储用户名
				if (loginForm.rememberMe) {
					localStorage.setItem("username", loginForm.username);
				} else {
					localStorage.removeItem("username");
				}

				ElMessage.success("登录成功");

				// 处理重定向
				const redirect = route.query.redirect || "/";
				router.push(redirect);
			} else {
				throw new Error(message || "登录失败，请重试");
			}
		} catch (error) {
			// 处理错误情况
			if (error.response && error.response.data) {
				// 服务器返回的错误
				ElMessage.error(error.response.data.message || "登录失败，请重试");
			} else {
				// 其他错误
				ElMessage.error(error.message || "网络错误，请稍后重试");
			}
		} finally {
			loading.value = false;
		}
	};

	// 初始化表单（从localStorage读取保存的用户名）
	const initForm = () => {
		const savedUsername = localStorage.getItem("username");
		if (savedUsername) {
			loginForm.username = savedUsername;
			loginForm.rememberMe = true;
		}
	};

	return {
		loginForm,
		loginRules,
		loading,
		handleLogin,
		initForm,
	};
}
